package cn.tedu.charging.order.timer;

import cn.tedu.charging.common.pojo.po.ChargingBillExceptionPO;
import cn.tedu.charging.common.pojo.po.ChargingBillSuccessPO;
import cn.tedu.charging.common.protocol.WebSocketMessage;
import cn.tedu.charging.order.mapper.BillExceptionMapper;
import cn.tedu.charging.order.mapper.BillSuccessMapper;
import cn.tedu.charging.order.websocket.WebSocketServer;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@Slf4j
public class OrderTimeJob {
    @Resource
    private BillSuccessMapper billSuccessMapper;
    @Resource
    private BillExceptionMapper billExceptionMapper;
    @Resource
    private WebSocketServer webSocketServer;
    // 准备一个job-handler
    @XxlJob("order-status-check")
    public void orderStatusCheck() {
        log.info("定时任务执行中...");
        // 1.拿到参数 orderId xxl-job传递过来的 从上下文中获取
        String orderId = XxlJobContext.getXxlJobContext().getJobParam();
        QueryWrapper<ChargingBillSuccessPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bill_id", orderId);
        ChargingBillSuccessPO chargingBSPO = billSuccessMapper.selectOne(queryWrapper);
        Integer status = chargingBSPO.getBillStatus();
        log.info("订单状态为:{}", status);
        if (status == 1) {
            // 按照异常单,充电长时间未结束处理.立刻结束
            ChargingBillExceptionPO PO = new ChargingBillExceptionPO();
            // 关于异常单的其他属性,可以通过创建任务传递param参数扩展
            PO.setBillId(orderId);
            PO.setCreateTime(new Date());
            billExceptionMapper.insert(PO);
            UpdateWrapper<ChargingBillSuccessPO> updateWrapper = new UpdateWrapper<>();
            // 修改订单状态 把status=1变成status=3
            updateWrapper.eq("bill_id", orderId);
            updateWrapper.set("bill_status", 3);
            billSuccessMapper.update(null, updateWrapper);
            // 推送用户端下单异常
            WebSocketMessage<String> wsm = new WebSocketMessage<>();
            // state=1表示订单有问题 2用户余额不足 3正常同步充电进度
            wsm.setState(1);
            wsm.setMessage("订单失败 请换枪");
            wsm.setData("A扫码下单失败，请换枪，非常抱歉，赠送您一张优惠券:http：//AN0df32fj3");
            webSocketServer.sendMessage(chargingBSPO.getUserId(),wsm);
        }
    }
}
